/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Telas;

import Beans.BeanAcesso;
import Beans.BeanTela;
import Beans.BeanUsuario;
import CRUD.CRUDAcesso;
import CRUD.CRUDTela;
import CRUD.CRUDUsuario;
import TableModel.AcessoTableModel;
import java.awt.Color;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Marcos
 */
public class Jp_Acesso extends javax.swing.JPanel {

    public static AcessoTableModel TMAcesso;
    List<BeanUsuario> ListaUsuario;
    List<BeanAcesso> ListaAcesso;
    List<BeanTela> ListaTela;
    String cod_usuario;

    /**
     * Creates new form Jp_Acesso
     */
    public Jp_Acesso() {
        initComponents();
        try {
            listUsuario();
            //listaacesso(); 
            listTela();
        } catch (Exception ex) {
            Logger.getLogger(Jp_Acesso.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabelUsuario = new javax.swing.JLabel();
        jComboBoxUsuario = new javax.swing.JComboBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTableAcesso = new javax.swing.JTable();
        jTextFieldCodUsuario = new javax.swing.JTextField();
        jButtonLiberarAcesso = new javax.swing.JButton();
        jLabelBarraStatus = new javax.swing.JLabel();
        jButtonBloquearAcesso = new javax.swing.JButton();
        jLabelTela = new javax.swing.JLabel();
        jComboBoxTela = new javax.swing.JComboBox();
        jTextFieldCodTela = new javax.swing.JTextField();
        jButtonVerificarAcesso = new javax.swing.JButton();

        setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        jLabelUsuario.setText("Usuário:");

        jComboBoxUsuario.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        jComboBoxUsuario.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                jComboBoxUsuarioFocusLost(evt);
            }
        });

        jTableAcesso.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jScrollPane1.setViewportView(jTableAcesso);

        jTextFieldCodUsuario.setEnabled(false);

        jButtonLiberarAcesso.setMnemonic('l');
        jButtonLiberarAcesso.setText("Liberar Acesso");
        jButtonLiberarAcesso.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonLiberarAcessoActionPerformed(evt);
            }
        });

        jLabelBarraStatus.setFont(new java.awt.Font("sansserif", 1, 12)); // NOI18N
        jLabelBarraStatus.setForeground(new java.awt.Color(255, 0, 51));

        jButtonBloquearAcesso.setMnemonic('b');
        jButtonBloquearAcesso.setText("Bloquear Acesso");

        jLabelTela.setText("Tela:");

        jComboBoxTela.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        jComboBoxTela.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                jComboBoxTelaFocusLost(evt);
            }
        });

        jTextFieldCodTela.setEnabled(false);

        jButtonVerificarAcesso.setMnemonic('v');
        jButtonVerificarAcesso.setText("Verificar Acesso");
        jButtonVerificarAcesso.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonVerificarAcessoActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabelBarraStatus, javax.swing.GroupLayout.PREFERRED_SIZE, 426, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jLabelTela)
                                    .addComponent(jLabelUsuario))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(jComboBoxUsuario, 0, 193, Short.MAX_VALUE)
                                    .addComponent(jComboBoxTela, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(jTextFieldCodUsuario, javax.swing.GroupLayout.DEFAULT_SIZE, 89, Short.MAX_VALUE)
                                    .addComponent(jTextFieldCodTela))))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButtonVerificarAcesso)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButtonLiberarAcesso)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonBloquearAcesso)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelUsuario)
                    .addComponent(jComboBoxUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextFieldCodUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelTela)
                    .addComponent(jComboBoxTela, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextFieldCodTela, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 186, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonLiberarAcesso)
                    .addComponent(jButtonBloquearAcesso)
                    .addComponent(jButtonVerificarAcesso))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabelBarraStatus, javax.swing.GroupLayout.PREFERRED_SIZE, 15, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jComboBoxUsuarioFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jComboBoxUsuarioFocusLost
        try {
            listausuariocod();
        } catch (SQLException ex) {
            Logger.getLogger(Jp_Acesso.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParseException ex) {
            Logger.getLogger(Jp_Acesso.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jComboBoxUsuarioFocusLost

    private void jButtonLiberarAcessoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonLiberarAcessoActionPerformed
        if (jTextFieldCodUsuario.getText().equals("")) {
            JOptionPane.showMessageDialog(null, "Selecione um usuário!", "Atenção", JOptionPane.WARNING_MESSAGE);
            jComboBoxUsuario.grabFocus();
        } else if (jTextFieldCodTela.getText().equals("")) {
            JOptionPane.showMessageDialog(null, "Selecione uma tela!", "Atenção", JOptionPane.WARNING_MESSAGE);
            jComboBoxTela.grabFocus();
        } else {
            cadastro();
        }
    }//GEN-LAST:event_jButtonLiberarAcessoActionPerformed

    private void jComboBoxTelaFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jComboBoxTelaFocusLost
        try {
            listatelacod();
        } catch (SQLException ex) {
            Logger.getLogger(Jp_Acesso.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParseException ex) {
            Logger.getLogger(Jp_Acesso.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jComboBoxTelaFocusLost

    private void jButtonVerificarAcessoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonVerificarAcessoActionPerformed
        if (jTextFieldCodUsuario.getText().equals("")) {
            JOptionPane.showMessageDialog(null, "Selecione um usuário!", "Atenção", JOptionPane.WARNING_MESSAGE);
            jComboBoxUsuario.grabFocus();
        } else {
            try {
                listaacessousuario();
            } catch (SQLException ex) {
                Logger.getLogger(Jp_Acesso.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ParseException ex) {
                Logger.getLogger(Jp_Acesso.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }//GEN-LAST:event_jButtonVerificarAcessoActionPerformed

    public void listausuariocod() throws SQLException, ParseException {
        CRUDUsuario CRUDUsua = new CRUDUsuario();
        ListaUsuario = CRUDUsua.getListaUsuarioNom(jComboBoxUsuario.getSelectedItem().toString());
        mostraUsuarioCod(ListaUsuario);
    }

    public void listatelacod() throws SQLException, ParseException {
        CRUDTela CRUDTela = new CRUDTela();
        ListaTela = CRUDTela.getListaTelaNom(jComboBoxTela.getSelectedItem().toString());
        mostraTelaCod(ListaTela);
    }

    public void listaacesso() throws SQLException, ParseException {
        CRUDAcesso CA = new CRUDAcesso();
        ListaAcesso = CA.getListaAcesso();
        //ListaAcesso = CA.getListaAcesso();        
        TMAcesso = new AcessoTableModel(ListaAcesso);
        jTableAcesso.setModel(TMAcesso);
        carregardados();
    }

    public void listaacessousuario() throws SQLException, ParseException {
        CRUDAcesso CA = new CRUDAcesso();
        ListaAcesso = CA.getListaAcessoUsuario(jComboBoxUsuario.getSelectedItem().toString());
        //ListaAcesso = CA.getListaAcesso();        
        TMAcesso = new AcessoTableModel(ListaAcesso);
        jTableAcesso.setModel(TMAcesso);
        carregardados();
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonBloquearAcesso;
    private javax.swing.JButton jButtonLiberarAcesso;
    private javax.swing.JButton jButtonVerificarAcesso;
    private javax.swing.JComboBox jComboBoxTela;
    private javax.swing.JComboBox jComboBoxUsuario;
    private javax.swing.JLabel jLabelBarraStatus;
    private javax.swing.JLabel jLabelTela;
    private javax.swing.JLabel jLabelUsuario;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTableAcesso;
    private javax.swing.JTextField jTextFieldCodTela;
    private javax.swing.JTextField jTextFieldCodUsuario;
    // End of variables declaration//GEN-END:variables

    public void limpardados() {
        jTextFieldCodUsuario.setText(null);
        jTextFieldCodTela.setText(null);
        jComboBoxUsuario.setSelectedIndex(0);
        jComboBoxTela.setSelectedIndex(0);
    }

    public void carregardados() {
        int col = 0;
        jTableAcesso.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); //barra horizontal na JTable 
        jTableAcesso.getColumnModel().getColumn(col++).setPreferredWidth(20); // Acertar Tamanho de cada coluna
        jTableAcesso.getColumnModel().getColumn(col++).setPreferredWidth(400);
    }

    private void listUsuario() throws Exception {
        jComboBoxUsuario.removeAllItems();

        BeanUsuario Seleciona = new BeanUsuario();
        Seleciona.setUsuario("Selecione um Usuário");
        jComboBoxUsuario.addItem(Seleciona);

        CRUDUsuario CRUDUsua = new CRUDUsuario();
        List<BeanUsuario> listausuario;

        jComboBoxUsuario.setEnabled(true);
        listausuario = CRUDUsua.getListaUsuario();

        Iterator<BeanUsuario> itusuario = listausuario.iterator();
        while (itusuario.hasNext()) {
            BeanUsuario BU = itusuario.next();
            jComboBoxUsuario.addItem(BU);
        }
    }

    private void listTela() throws Exception {
        jComboBoxTela.removeAllItems();

        BeanTela Seleciona = new BeanTela();
        Seleciona.setDen_tela("Selecione uma Tela");
        jComboBoxTela.addItem(Seleciona);

        CRUDTela CRUDTel = new CRUDTela();
        List<BeanTela> listaacesso;

        jComboBoxTela.setEnabled(true);
        listaacesso = CRUDTel.getListaTela();

        Iterator<BeanTela> ittela = listaacesso.iterator();
        while (ittela.hasNext()) {
            BeanTela BT = ittela.next();
            jComboBoxTela.addItem(BT);
        }
    }

    private void mostraUsuarioCod(List<BeanUsuario> ListaUsuario) {
        for (int i = 0; i < ListaUsuario.size(); i++) {
            String cod_usuario = String.valueOf(ListaUsuario.get(i).getCod_usuario());
            jTextFieldCodUsuario.setText(cod_usuario);
        }
    }
    
    private void mostraTelaCod(List<BeanTela> ListaTela) {
        for (int i = 0; i < ListaTela.size(); i++) {
            String cod_tela = String.valueOf(ListaTela.get(i).getCod_tela());
            jTextFieldCodTela.setText(cod_tela);
        }
    }

    
    private void cadastro() {
        try {
            BeanAcesso BA = new BeanAcesso();
            BA.setCod_usuario(Integer.valueOf(jTextFieldCodUsuario.getText()));
            BA.setCod_tela(Integer.valueOf(jTextFieldCodTela.getText()));
            CRUDAcesso dao = new CRUDAcesso();
            dao.adiciona(BA);
            limpardados();
            jLabelBarraStatus.setText("Acesso Liberado!!!");
            threadR(jLabelBarraStatus);

            try {
                listaacessousuario();
            } catch (ParseException ex) {
                Logger.getLogger(Jp_Acesso.class.getName()).log(Level.SEVERE, null, ex);
            }

        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Usuário já cadastrado para essa tela!", "Atenção", JOptionPane.WARNING_MESSAGE);
            Logger.getLogger(Jp_Acesso.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void threadR(final JLabel label) {
        Thread tThread = new Thread(new Runnable() {
            @Override
            public void run() {

                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {

                    e.printStackTrace();
                }
                //repaint();    
                label.setText("");

            }
        });
        tThread.start();
    }   
}